﻿using System;
using System.Windows.Input;
using Client.Wpf.HelloServiceReference;
using Client.Wpf.ViewModels;

namespace Client.Wpf.Commands
{
  public class SendMessageCommand : ICommand
  {
    private readonly IResult _result;
    private readonly IHelloService _service;

    public SendMessageCommand(IHelloService service, IResult result)
    {
      _service = service;
      _result = result;
    }

    public void Execute(object parameter)
    {
      var name = parameter as string;
      if (name == null) return;

      _service.BeginSayHello(name, Callback, _service);
    }

    public bool CanExecute(object parameter)
    {
      return true;
    }

    public event EventHandler CanExecuteChanged;

    protected virtual void OnCanExecuteChanged()
    {
      EventHandler handler = CanExecuteChanged;
      if (handler != null) handler(this, EventArgs.Empty);
    }

    private void Callback(IAsyncResult ar)
    {
      var service = (IHelloService) ar.AsyncState;
      _result.Result = service.EndSayHello(ar);
    }
  }
}